package com.appkubes.mall.restful.application.user.address.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.cloud.config.params.paramValid.ParamValid;
import com.appkubes.common.Response;
import com.appkubes.mall.core.entity.MallUserAddress;
import com.appkubes.mall.restful.application.common.base.BaseController;
import com.appkubes.mall.restful.application.user.address.entity.dto.AddressDTO;
import com.appkubes.mall.restful.application.user.address.entity.vo.AddUserAddressVo;
import com.appkubes.mall.restful.application.user.address.entity.vo.DelUserAddressVo;
import com.appkubes.mall.restful.application.user.address.entity.vo.EditUserAddressVo;
import com.appkubes.mall.restful.application.user.address.entity.vo.MallUserAddressVo;
import com.appkubes.mall.restful.application.user.address.service.UserAddressService;
import com.appkubes.mall.restful.application.user.address.service.impl.UserAddressServiceImpl;
import com.appkubes.mall.restful.application.user.user.service.impl.UserServiceLoginImpl;
import com.appkubes.mall.restful.config.camel.RequestModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Api("用户地址模块")
@RestController
@RequestMapping("/api/Cuseraddress")
@Slf4j
public class UserAddressController extends BaseController {


    @Autowired
    UserAddressServiceImpl userAddressServiceImpl;

    @Autowired
    UserServiceLoginImpl userServiceImpl;

    @Autowired
    UserAddressService userAddressService;

    @ApiOperation(value = "获取地址")
    @PostMapping("/lists")
    public Object lists(@RequestBody @Valid MallUserAddressVo mallUserAddressVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Response.error("参数错误");
        }
        List<MallUserAddress> list = new ArrayList<>();
        list = userAddressServiceImpl.querySelective(mallUserAddressVo.getUserKey(), null);

        return Response.success(list);
    }

    @ApiOperation(value = "添加地址")
    @PostMapping("/add")
    public Object add(@RequestBody @ParamValid AddUserAddressVo addUserAddressVo) {
        log.info("add: {}", addUserAddressVo);

        MallUserAddress mallUserAddress = new MallUserAddress();
        BeanUtils.copyProperties(addUserAddressVo, mallUserAddress);

        // tag
        JSONArray jsonArray = new JSONArray();

        mallUserAddress.setIsDefault((int) addUserAddressVo.getIsDefault());
        mallUserAddress.setTag(jsonArray.toJSONString());
        mallUserAddress.setAppKey(null);
        userAddressServiceImpl.save(mallUserAddress);
        String key = mallUserAddress.getUserAddressKey();

        log.info("add address success: {}", key);
        if (mallUserAddress.getIsDefault() != null && mallUserAddress.getIsDefault() == (byte) 1) {
            userAddressServiceImpl.setDefault(mallUserAddress.getUserKey(), mallUserAddress.getUserAddressKey());
        }
        Integer count = userAddressServiceImpl.querySelective(mallUserAddress.getUserKey(), null).size();
        if (count == 1) {
            userAddressServiceImpl.setDefault(mallUserAddress.getUserKey(), key);
        }

        return Response.success();
    }

    @ApiOperation(value = "小程序")
    @PostMapping("/editWx")
    public Object editWx(@RequestBody MallUserAddress model) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tag", model.getTag());
        model.setTag(jsonObject.toJSONString());
        System.out.println(model);
        userAddressServiceImpl.updateById(model);

        if (model.getIsDefault() == (byte) 1) {
            userAddressServiceImpl.setDefault(model.getUserKey(), model.getUserAddressKey());
        } else {

        }
        return Response.success();
    }

    @ApiOperation(value = "修改地址")
    @PostMapping("/edit")
    public Object edit(@RequestModel MallUserAddress model,
                       @RequestParam(defaultValue = "0") int isDefalutPhone,
                       @RequestParam(defaultValue = "0") int isDefault,
                       @RequestParam(defaultValue = "") String userKey,
                       @RequestParam(defaultValue = "") String saasUserid,
                       @RequestParam(defaultValue = "") String appKey) {

        if (!StringUtils.isEmpty(userKey) && isDefault == 1) {
            userAddressServiceImpl.setDefault(userKey, model.getUserAddressKey());
        } else if (!StringUtils.isEmpty(saasUserid) && isDefault == 1) {
            userAddressServiceImpl.setDefaultByUid(model.getUserAddressKey());
        }
        return Response.success();
    }

    @ApiOperation(value = "获取默认")
    @PostMapping("/getDefault")
    public Object getDefault(@RequestBody @Valid MallUserAddressVo mallUserAddressVo) {
        AddressDTO addressDTO = new AddressDTO();
        MallUserAddress mallUserAddress = userAddressService.getDefault(mallUserAddressVo);
        BeanUtils.copyProperties(mallUserAddress, addressDTO);
        addressDTO.setArea(mallUserAddress.getDistrict());
        if ("市辖区".equals(addressDTO.getCity())) {
            addressDTO.setCity("");
        }
        return Response.success(addressDTO);
    }

    @ApiOperation(value = "地址详细")
    @PostMapping("/detail")
    public Object detail(@RequestBody @ParamValid EditUserAddressVo editUserAddressVo) {
        return Response.success(userAddressServiceImpl.getById(editUserAddressVo.getUserAddressKey()));
    }

    @ApiOperation(value = "设置默认")
    @PostMapping("/setDefault")
    public Object setDefault(@RequestBody @ParamValid MallUserAddressVo mallUserAddressVo) {
        Boolean result = userAddressService.setDefault(mallUserAddressVo);
        return Response.success(result);
    }

    @ApiOperation(value = "删除地址")
    @PostMapping("/del")
    public Object del(@RequestBody @Valid DelUserAddressVo delUserAddressVo, BindingResult bindingResult) {
        MallUserAddress model = userAddressServiceImpl.getById(delUserAddressVo.getUserAddressKey());
        Integer isDefault = model.getIsDefault();
        userAddressServiceImpl.removeById(delUserAddressVo.getUserAddressKey());
        if (isDefault == 1) {
            //原系统业务有bug
            List<MallUserAddress> list = new ArrayList<>();
            if (!StringUtils.isEmpty(delUserAddressVo.getUserKey())) {
                list = userAddressServiceImpl.querySelective(delUserAddressVo.getUserKey(), 0);
            }
            if (list.size() > 0) {
                MallUserAddress address = list.get(0);
                address.setIsDefault(1);
                userAddressServiceImpl.updateById(address);
            }
        }


        return Response.success();
    }
}














